/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xuidemo.util;

import com.google.gson.Gson;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONException;
import ohos.utils.zson.ZSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析类
 *
 * @author zyyoona7
 * @version v1.0
 * @since 2018-08-21
 */
public class ParseHelper {
    /**
     * json数据1
     */
    public static final String NAME_AREA_LEVEL_2 = "resources/rawfile/AreaLevel_2.json";
    /**
     * json数据2
     */
    public static final String NAME_AREA_LEVEL_3 = "resources/rawfile/AreaLevel_3.json";

    private static final String TAG = "ParseHelper";
    private static HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x001, TAG);

    /**
     * 构造
     */
    private ParseHelper() {
    }

    /**
     * 初始化二级城市列表
     *
     * @param context
     * @param oneList
     * @param twoList
     */
    public static void initTwoLevelCityList(Context context, List<CityEntity> oneList, List<List<CityEntity>> twoList) {
        List<CityEntity> twoLevelList = parseTwoLevelCityList(context);
        oneList.addAll(twoLevelList);
        for (CityEntity cityEntity : twoLevelList) {
            List<CityEntity> cityList = new ArrayList<>(1);
            List<CityEntity> subCityList = cityEntity.getDistricts();
            cityList.addAll(subCityList);

            twoList.add(cityList);
        }
    }

    /**
     * 初始化三级城市列表
     *
     * @param context
     * @param oneList
     * @param twoList
     * @param threeList
     */
    public static void initThreeLevelCityList(Context context, List<CityEntity> oneList,
                                              List<List<CityEntity>> twoList, List<List<List<CityEntity>>> threeList) {
        List<CityEntity> threeLevelCityList = parseThreeLevelCityList(context);
        oneList.addAll(threeLevelCityList);
        for (CityEntity cityEntity : threeLevelCityList) {
            List<CityEntity> cityList = new ArrayList<>(1);
            List<List<CityEntity>> arethreeList = new ArrayList<>(1);
            List<CityEntity> subCityList = cityEntity.getDistricts();
            for (CityEntity entity : subCityList) {
                cityList.add(entity);
                arethreeList.add(entity.getDistricts());
            }
            twoList.add(cityList);
            threeList.add(arethreeList);
        }
    }

    private static void initCityList(List<CityEntity> parseList,
                                     List<CityEntity> oneList, List<List<CityEntity>> twoList,
                                     List<List<List<CityEntity>>> threeList, boolean isThreeLevel) {
        if (parseList == null) {
            return;
        }
        for (CityEntity cityEntity : parseList) {
            List<CityEntity> cityList = new ArrayList<>(1);
            if (isThreeLevel) {
//                List<List<CityEntity>> arethreeList = new ArrayList<>(1);
            }
            List<CityEntity> subCityList = cityEntity.getDistricts();
            cityList.addAll(subCityList);
        }
    }

    /**
     * 解析出二级城市列表
     *
     * @param context
     * @return 二级城市列表
     */
    public static List<CityEntity> parseTwoLevelCityList(Context context) {
        return parseCityList(context, NAME_AREA_LEVEL_2);
    }

    /**
     * 解析出三级城市列表
     *
     * @param context
     * @return 三级城市列表
     */
    public static List<CityEntity> parseThreeLevelCityList(Context context) {
        return parseCityList(context, NAME_AREA_LEVEL_3);
    }

    /**
     * 解析城市数据
     *
     * @param context
     * @param assetFileName
     * @return  List<CityEntity> 城市实体数组
     */
    private static List<CityEntity> parseCityList(Context context, String assetFileName) {
        ohos.global.resource.ResourceManager resManager = context.getResourceManager();
        ohos.global.resource.RawFileEntry rawFileEntry = resManager.getRawFileEntry(assetFileName);
        /**
         * 将json数据变成字符串
         */
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    rawFileEntry.openRawFile()));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            HiLog.error(logLabel, e.getMessage());
        }
        try {
            ZSONObject zsonObject = new ZSONObject();
            ZSONObject zsonObject1 = zsonObject.stringToZSON(stringBuilder.toString());
            ZSONArray jsonArray = zsonObject1.getZSONArray("districts");
            ZSONObject countryJobj = jsonArray.getZSONObject(0);
            String contentString = countryJobj.getString("districts");
            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(String.class, new CityEntityStringJsonDeserializer())
                    .create();
            return gson.fromJson(contentString, new TypeToken<List<CityEntity>>() {
            }.getType());
        } catch (ZSONException e) {
            HiLog.error(logLabel, "城市列表 JSON 数据解析异常：" + e.getMessage());
        }
        return new ArrayList<>(1);
    }

    /**
     * 反序列化
     *
     * @since 2018-08-21
     */
    public static class CityEntityStringJsonDeserializer implements JsonDeserializer<String> {
        @Override
        public String deserialize(JsonElement json, Type typeOfT,
                                  JsonDeserializationContext context) throws JsonParseException {
            try {
                return json.getAsString();
            } catch (Exception e) {
                return "";
            }
        }
    }
}
